<template>
  <div class="data-table-container">
    <!-- 表格工具栏 -->
    <div class="table-toolbar" v-if="showToolbar">
      <div class="toolbar-left">
        <slot name="toolbar-left">
          <div class="table-title" v-if="title">{{ title }}</div>
        </slot>
      </div>
      <div class="toolbar-right">
        <slot name="toolbar-right">
          <!-- 刷新按钮 -->
          <el-button
            v-if="showRefresh"
            @click="handleRefresh"
            :loading="loading"
            circle
            size="small"
          >
            <Icon icon="ep:refresh" />
          </el-button>
          
          <!-- 列设置 -->
          <el-popover
            v-if="showColumnSetting"
            placement="bottom-end"
            width="200"
            trigger="click"
          >
            <template #reference>
              <el-button circle size="small">
                <Icon icon="ep:setting" />
              </el-button>
            </template>
            <div class="column-setting">
              <div class="setting-title">列显示设置</div>
              <el-checkbox-group v-model="visibleColumns">
                <div
                  v-for="column in settableColumns"
                  :key="column.prop"
                  class="column-item"
                >
                  <el-checkbox :label="column.prop">
                    {{ column.label }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </el-popover>
          
          <!-- 导出按钮 -->
          <el-button
            v-if="showExport"
            @click="handleExport"
            :loading="exportLoading"
            size="small"
          >
            <Icon icon="ep:download" class="mr-1" />
            导出
          </el-button>
        </slot>
      </div>
    </div>

    <!-- 表格主体 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="data"
      :stripe="stripe"
      :border="border"
      :show-overflow-tooltip="showOverflowTooltip"
      :row-key="rowKey"
      :tree-props="treeProps"
      :expand-row-keys="expandRowKeys"
      :default-expand-all="defaultExpandAll"
      :selection-change="handleSelectionChange"
      :sort-change="handleSortChange"
      :filter-change="handleFilterChange"
      :row-click="handleRowClick"
      :row-dblclick="handleRowDblclick"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      :row-style="rowStyle"
      :height="height"
      :max-height="maxHeight"
      class="data-table"
    >
      <!-- 选择列 -->
      <el-table-column
        v-if="showSelection"
        type="selection"
        width="55"
        align="center"
        :selectable="selectable"
      />

      <!-- 序号列 -->
      <el-table-column
        v-if="showIndex"
        type="index"
        label="序号"
        width="60"
        align="center"
        :index="indexMethod"
      />

      <!-- 动态列 -->
      <template v-for="column in displayColumns" :key="column.prop">
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :align="column.align || 'center'"
          :sortable="column.sortable"
          :filters="column.filters"
          :filter-method="column.filterMethod"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
        >
          <template #default="scope" v-if="column.slot">
            <slot :name="column.slot" :row="scope.row" :column="column" :index="scope.$index">
              {{ scope.row[column.prop] }}
            </slot>
          </template>
          <template #default="scope" v-else-if="column.formatter">
            {{ column.formatter(scope.row, column, scope.row[column.prop], scope.$index) }}
          </template>
        </el-table-column>
      </template>

      <!-- 操作列 -->
      <el-table-column
        v-if="showActions"
        label="操作"
        :width="actionWidth"
        :fixed="actionFixed"
        align="center"
      >
        <template #default="scope">
          <slot name="actions" :row="scope.row" :index="scope.$index">
            <el-button
              v-for="action in getRowActions(scope.row)"
              :key="action.key"
              :type="action.type || 'primary'"
              :size="action.size || 'small'"
              :disabled="action.disabled"
              :loading="action.loading"
              link
              @click="handleAction(action, scope.row, scope.$index)"
            >
              <Icon v-if="action.icon" :icon="action.icon" class="mr-1" />
              {{ action.label }}
            </el-button>
          </slot>
        </template>
      </el-table-column>

      <!-- 空数据插槽 -->
      <template #empty>
        <slot name="empty">
          <el-empty description="暂无数据" />
        </slot>
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="table-pagination" v-if="showPagination">
      <Pagination
        :total="total"
        v-model:page="currentPage"
        v-model:limit="currentPageSize"
        @pagination="handlePagination"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  fixed?: boolean | 'left' | 'right'
  align?: 'left' | 'center' | 'right'
  sortable?: boolean | 'custom'
  filters?: Array<{ text: string; value: any }>
  filterMethod?: Function
  formatter?: Function
  slot?: string
  showOverflowTooltip?: boolean
  settable?: boolean
}

interface TableAction {
  key: string
  label: string
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info'
  size?: 'large' | 'default' | 'small'
  icon?: string
  disabled?: boolean
  loading?: boolean
  show?: (row: any) => boolean
}

interface Props {
  /** 表格标题 */
  title?: string
  /** 表格数据 */
  data: any[]
  /** 表格列配置 */
  columns: TableColumn[]
  /** 是否显示工具栏 */
  showToolbar?: boolean
  /** 是否显示选择列 */
  showSelection?: boolean
  /** 是否显示序号列 */
  showIndex?: boolean
  /** 是否显示操作列 */
  showActions?: boolean
  /** 操作列宽度 */
  actionWidth?: string | number
  /** 操作列固定 */
  actionFixed?: boolean | 'left' | 'right'
  /** 行操作配置 */
  actions?: TableAction[]
  /** 是否显示分页 */
  showPagination?: boolean
  /** 总数据量 */
  total?: number
  /** 当前页码 */
  page?: number
  /** 每页大小 */
  pageSize?: number
  /** 是否加载中 */
  loading?: boolean
  /** 是否显示刷新按钮 */
  showRefresh?: boolean
  /** 是否显示列设置 */
  showColumnSetting?: boolean
  /** 是否显示导出按钮 */
  showExport?: boolean
  /** 导出加载状态 */
  exportLoading?: boolean
  /** 表格高度 */
  height?: string | number
  /** 表格最大高度 */
  maxHeight?: string | number
  /** 是否显示斑马纹 */
  stripe?: boolean
  /** 是否显示边框 */
  border?: boolean
  /** 是否显示溢出提示 */
  showOverflowTooltip?: boolean
  /** 行数据的 Key */
  rowKey?: string
  /** 树形数据配置 */
  treeProps?: object
  /** 默认展开的行 */
  expandRowKeys?: any[]
  /** 是否默认展开所有行 */
  defaultExpandAll?: boolean
  /** 选择函数 */
  selectable?: (row: any, index: number) => boolean
  /** 表头样式 */
  headerCellStyle?: object | Function
  /** 单元格样式 */
  cellStyle?: object | Function
  /** 行样式 */
  rowStyle?: object | Function
}

const props = withDefaults(defineProps<Props>(), {
  showToolbar: true,
  showSelection: false,
  showIndex: false,
  showActions: true,
  actionWidth: 200,
  actionFixed: 'right',
  actions: () => [],
  showPagination: true,
  total: 0,
  page: 1,
  pageSize: 10,
  loading: false,
  showRefresh: true,
  showColumnSetting: true,
  showExport: false,
  exportLoading: false,
  stripe: true,
  border: false,
  showOverflowTooltip: true,
  defaultExpandAll: false
})

const emit = defineEmits<{
  'refresh': []
  'export': []
  'selection-change': [selection: any[]]
  'sort-change': [sort: any]
  'filter-change': [filters: any]
  'row-click': [row: any, column: any, event: Event]
  'row-dblclick': [row: any, column: any, event: Event]
  'action-click': [action: TableAction, row: any, index: number]
  'pagination': [page: number, pageSize: number]
  'update:page': [page: number]
  'update:pageSize': [pageSize: number]
}>()

const tableRef = ref()
const visibleColumns = ref<string[]>([])
const currentPage = ref(props.page)
const currentPageSize = ref(props.pageSize)

/** 可设置的列 */
const settableColumns = computed(() => {
  return props.columns.filter(column => column.settable !== false)
})

/** 显示的列 */
const displayColumns = computed(() => {
  return props.columns.filter(column => 
    column.settable === false || visibleColumns.value.includes(column.prop)
  )
})

/** 序号方法 */
const indexMethod = (index: number) => {
  return (currentPage.value - 1) * currentPageSize.value + index + 1
}

/** 获取行操作 */
const getRowActions = (row: any) => {
  return props.actions.filter(action => 
    !action.show || action.show(row)
  )
}

/** 处理刷新 */
const handleRefresh = () => {
  emit('refresh')
}

/** 处理导出 */
const handleExport = () => {
  emit('export')
}

/** 处理选择变化 */
const handleSelectionChange = (selection: any[]) => {
  emit('selection-change', selection)
}

/** 处理排序变化 */
const handleSortChange = (sort: any) => {
  emit('sort-change', sort)
}

/** 处理筛选变化 */
const handleFilterChange = (filters: any) => {
  emit('filter-change', filters)
}

/** 处理行点击 */
const handleRowClick = (row: any, column: any, event: Event) => {
  emit('row-click', row, column, event)
}

/** 处理行双击 */
const handleRowDblclick = (row: any, column: any, event: Event) => {
  emit('row-dblclick', row, column, event)
}

/** 处理操作点击 */
const handleAction = (action: TableAction, row: any, index: number) => {
  emit('action-click', action, row, index)
}

/** 处理分页 */
const handlePagination = (page: number, pageSize: number) => {
  currentPage.value = page
  currentPageSize.value = pageSize
  emit('update:page', page)
  emit('update:pageSize', pageSize)
  emit('pagination', page, pageSize)
}

/** 初始化可见列 */
const initVisibleColumns = () => {
  visibleColumns.value = settableColumns.value.map(column => column.prop)
}

/** 监听页码变化 */
watch(() => props.page, (newPage) => {
  currentPage.value = newPage
})

/** 监听页大小变化 */
watch(() => props.pageSize, (newPageSize) => {
  currentPageSize.value = newPageSize
})

/** 暴露表格方法 */
defineExpose({
  getTableRef: () => tableRef.value,
  clearSelection: () => tableRef.value?.clearSelection(),
  toggleRowSelection: (row: any, selected?: boolean) => tableRef.value?.toggleRowSelection(row, selected),
  toggleAllSelection: () => tableRef.value?.toggleAllSelection(),
  toggleRowExpansion: (row: any, expanded?: boolean) => tableRef.value?.toggleRowExpansion(row, expanded),
  setCurrentRow: (row: any) => tableRef.value?.setCurrentRow(row),
  clearSort: () => tableRef.value?.clearSort(),
  clearFilter: (columnKeys?: string[]) => tableRef.value?.clearFilter(columnKeys),
  doLayout: () => tableRef.value?.doLayout(),
  sort: (prop: string, order: string) => tableRef.value?.sort(prop, order)
})

/** 初始化 */
onMounted(() => {
  initVisibleColumns()
})
</script>

<style scoped>
.data-table-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.toolbar-left {
  flex: 1;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.column-setting {
  max-height: 300px;
  overflow-y: auto;
}

.setting-title {
  font-weight: 600;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.column-item {
  margin-bottom: 8px;
}

.data-table {
  width: 100%;
}

.table-pagination {
  padding: 16px;
  border-top: 1px solid #e5e7eb;
}
</style>
